package cn.fl.custpay.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.user.facade.framework.constant.DictionaryConstant;
import cn.cmm.base.framework.utils.*;
import cn.fl.custpay.condition.CmmOlRecordDetailQueryCondition;
import cn.fl.custpay.service.ICmmCstAddressService;
import cn.fl.custpay.service.ICmmOlRecordDetailService;
import cn.fl.custpay.vo.CmmOlRecordDetailVO;
import com.alibaba.fastjson.JSON;
import fl.customer.facade.customer.api.ICustomerApiService;
import fl.customer.facade.customer.api.ICustomerQueryApiService;
import fl.customer.facade.customer.condition.CstBankQueryCondition;
import fl.customer.facade.customer.dto.CstBankDTO;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.fl.custpay.condition.CmmRechargeRecordQueryCondition;
import cn.fl.custpay.constant.CustPayConstant;
import cn.fl.custpay.service.ICmmRechargeRecordService;
import cn.fl.custpay.vo.CmmRechargeRecordVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.lb.framework.poi.excel.ExcelExportUtil;
import cn.lb.framework.poi.excel.entity.ExportParams;
import cn.lb.framework.poi.excel.entity.enmus.ExcelType;
import cn.lb.framework.poi.excel.export.styler.ExcelExportStylerDefaultImpl;
import pay.business.facade.custpay.api.ICmmRechargeRecordApiService;

/**
 * @Description: 还款记录 控制层
 */
@Controller
@RequestMapping("/custpay/cmmRechargeRecord")
public class CmmRechargeRecordController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CmmRechargeRecordController.class);

	/**
	 * CmmRechargeRecord 服务层BEAN
	 */
	@Autowired
	private ICmmRechargeRecordService cmmRechargeRecordService;

	@Autowired
	private ISysUsrApiService sysUsrApiService;

	@Autowired
	private ICmmOlRecordDetailService cmmOlRecordDetailService;
	
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	@Autowired
	private ICustomerQueryApiService customerQueryApiService;



	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toCmmRechargeRecordList.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("custpay/cmmRechargeRecord/cmmRechargeRecordList");
		List<Map<String,String>> statuslist = new ArrayList<Map<String,String>>();
		Map<String,String> typemap1 = new HashMap<String,String>();
		typemap1.put("key","0");
		typemap1.put("value","失败");
		statuslist.add(typemap1);
		Map<String,String> typemap2 = new HashMap<String,String>();
		typemap2.put("key","1");
		typemap2.put("value","成功");
		statuslist.add(typemap2);
		Map<String,String> typemap3 = new HashMap<String,String>();
		typemap3.put("key","2");
		typemap3.put("value","未支付");
		statuslist.add(typemap3);
		Map<String,String> typemap4 = new HashMap<String,String>();
		typemap4.put("key","3");
		typemap4.put("value","已受理");
		statuslist.add(typemap4);
        Map<String,String> typemap5 = new HashMap<String,String>();
		typemap5.put("key","4");
		typemap5.put("value","已手动还款");
		statuslist.add(typemap5);
		List<KeyValueVO> orglist = this.cmmRechargeRecordService.searchListByOrgTypCd(CurrentThreadContext.getFlServiceSysCd());
		view.addObject("orglist", orglist);
		view.addObject("statuslist", statuslist);
		List<KeyValueVO> kvList = this.sysDictionaryApiService.getKvList(CustPayConstant.CUST_PAY_TYPPE_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		view.addObject("payTypList", kvList);
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("custpay/cmmRechargeRecord/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initCmmRechargeRecordList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String orderid = request.getParameter("orderid");
		String isSuc = request.getParameter("isSuc");
		String clientPhone = request.getParameter("clientPhone");
		String clientName = request.getParameter("clientName");
		String platformSeqId = request.getParameter("platformSeqId");
		String crtTmBegin = request.getParameter("crtTmBegin");
		String crtTmEnd = request.getParameter("crtTmEnd");
		String isAutoCharge = request.getParameter("isAutoCharge");
		String prpslSts = request.getParameter("prpslSts");
		String payType = request.getParameter("payType");
		String idCard = request.getParameter("idCard");

		//获取bank_id
		List<Long> bkids = new ArrayList<>();
		if (StringUtils.isNotEmpty(idCard)){
			BaseLogUtils.info(logger, "initList", "查询证件号:" + idCard);
			CstBankQueryCondition cstCondition = new CstBankQueryCondition();
			cstCondition.setCertNo(idCard);
			List<CstBankDTO> cstBankDTOS = customerQueryApiService.searchCstBankList(cstCondition);
			BaseLogUtils.info(logger, "initList", "查询bank_id是:" + JSONObject.toJSONString(cstBankDTOS));
			if (cstBankDTOS != null && cstBankDTOS.size() > 0){
				for (CstBankDTO dto: cstBankDTOS) {
					Long id = dto.getId();
					bkids.add(id);
				}
				BaseLogUtils.info(logger, "initList", "添加bank_id是:" + JSONObject.toJSONString(bkids));

			}
			if(CollectionUtils.isEmpty(bkids)){

				BaseLogUtils.info(logger, "initList", "根据省份证号未查到bk_id直接返回:" + JSONObject.toJSONString(bkids));
				return new ListPageVO<CmmRechargeRecordVO>(new ArrayList<>(), 0);
			}
		}
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CmmRechargeRecordQueryCondition qc = new CmmRechargeRecordQueryCondition();
		if(bkids != null && bkids.size()>0){
			BaseLogUtils.info(logger, "initList", "设置bank_id是:" + JSONObject.toJSONString(bkids));
			qc.setBankIds(bkids);
		}
		if (StringUtils.isNotEmpty(orderid)) {
			qc.setId(Long.valueOf(orderid));
		}
		if (StringUtils.isNotEmpty(isSuc)) {
			qc.setIsSuc(Integer.valueOf(isSuc));
		}
		if (StringUtils.isNotEmpty(clientPhone)) {
			qc.setClientPhone(clientPhone);
		}
		if (StringUtils.isNotEmpty(platformSeqId)) {
			qc.setPlatformSeqId(platformSeqId);
		}
		if (StringUtils.isNotEmpty(clientName)) {
			qc.setClientName(clientName);
		}
		if (StringUtils.isNotEmpty(crtTmBegin)) {
			qc.setCrtTmBegin(DateUtils.formatStringToDate(crtTmBegin,DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(crtTmEnd)) {
			qc.setCrtTmEnd(DateUtils.formatStringToDate(crtTmEnd, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(isAutoCharge)) {
			qc.setIsAutoCharge(Integer.valueOf(isAutoCharge));
		}
		if(StringUtils.isNotEmpty(prpslSts)){
			qc.setPrpslSts(Long.valueOf(prpslSts));
		}
		if(StringUtils.isNotEmpty(payType)){
			qc.setPayType(Long.valueOf(payType));
		}
		page.setCondition(qc);
		
		//TODO SOMETHING
		Pager pager = this.cmmRechargeRecordService.searchListPage(page);
		List<CmmRechargeRecordVO> list = (List<CmmRechargeRecordVO>)pager.getResultList();
		Map<String,String> prpslstsmap = new HashMap<String,String>();
		prpslstsmap.put("0","未处理");
		prpslstsmap.put("1","处理中");
		prpslstsmap.put("2","已处理");
		Map<String,String> sumap = new HashMap<String,String>();
		sumap.put("0","失败");
		sumap.put("1","成功");
		sumap.put("2","未支付");
		sumap.put("3","已受理");
		Map<String,String> commpaytypemap = new HashMap<String,String>();
		commpaytypemap.put("0","狮桥支付");
		commpaytypemap.put("1","用户支付");
		commpaytypemap.put("2","免费");
		/*Map<String,String> paytypemap = new HashMap<String,String>();
		paytypemap.put("1","汇付");
		paytypemap.put("2","信联");
        paytypemap.put("3","国付宝");
		paytypemap.put("4","平安");
		paytypemap.put("5","先锋");
		paytypemap.put("6","翼支付");
		paytypemap.put("7","易付宝");
		paytypemap.put("8","宝付");
		paytypemap.put("9","宝付协议");
		paytypemap.put("10","先锋协议");*/
		Map<String,String> paytypemap =  this.cmmRechargeRecordService.getDictionryMap(DictionaryConstant.SYS_PAY_CHANNEL_CD);
		Map<String,String> paymenttypemap = new HashMap<String,String>();
		paymenttypemap.put("1","快捷支付");
		paymenttypemap.put("2","代扣支付");
		Map<String,String> isautochargemap = new HashMap<String,String>();
		isautochargemap.put("1","是");
		isautochargemap.put("0","否");
		for(CmmRechargeRecordVO _vo : list){
			if(null != _vo.getIsSuc()){
				_vo.setIsSucNm(sumap.get(String.valueOf(_vo.getIsSuc())));
			}
			if(StringUtils.isNotEmpty(_vo.getPrpslSts())){
				_vo.setPrpslStsNm(prpslstsmap.get(String.valueOf(_vo.getPrpslSts())));
			}
			Long paymentmoney = _vo.getPaymentMoney()!=null?_vo.getPaymentMoney():0l;
			if(null != _vo.getPaymentMoney()){
				_vo.setPaymentMoneydou(DecimalUtils.convertFenToYuan(_vo.getPaymentMoney()));
				_vo.setFeeAmt(this.calFeeAmt(_vo.getPaymentMoney()));
			}
			if(StringUtils.isNotEmpty(_vo.getCommAmt())){
				_vo.setCommAmt(String.valueOf(DecimalUtils.convertFenToYuan(Long.valueOf(_vo.getCommAmt()))));
			}
			if(StringUtils.isNotEmpty(_vo.getPayComm())){
				_vo.setPayComm(String.valueOf(DecimalUtils.convertFenToYuan(Long.valueOf(_vo.getPayComm()))));
			}
			if(null != _vo.getCommPayType()){
				_vo.setCommPayTypeNm(commpaytypemap.get(String.valueOf(_vo.getCommPayType())));
			}
			if(null != _vo.getPayType()){
				if(paytypemap != null) {
					_vo.setPayTypeNm(paytypemap.get(String.valueOf(_vo.getPayType())));
				}
			}
			if(null != _vo.getPaymentType()){
				_vo.setPaymentTypeNm(paymenttypemap.get(String.valueOf(_vo.getPaymentType())));
			}
			if(null != _vo.getIsAutoCharge()){
				_vo.setIsAutoChargeNm(isautochargemap.get(String.valueOf(_vo.getIsAutoCharge())));
			}
			if(StringUtils.isNotEmpty(_vo.getMdfUsrId())){
				SysUsrDTO sysUsrDTO = this.sysUsrApiService.selectSysUsrById(_vo.getMdfUsrId(),CurrentThreadContext.getFlServiceSysCd(),CurrentThreadContext.getCurrentOrgCd());
				if(null != sysUsrDTO && StringUtils.isNotEmpty(sysUsrDTO.getRefRlNm())){
					_vo.setMdfUsrNm(sysUsrDTO.getRefRlNm());
				}
			}
		}
		ListPageVO<CmmRechargeRecordVO> listPage = new ListPageVO<CmmRechargeRecordVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/autoChargePay.do", method = { RequestMethod.GET})
	@ResponseBody
	public DataResultVO autoChargePay(HttpServletRequest request, HttpServletResponse response) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "代扣执行中...");
		BaseLogUtils.info(logger, "autoChargePay", "信联自动代扣手动触发====开始", CurrentThreadContext.getCurrentUserName());
		this.cmmRechargeRecordService.autoChargePay();
		BaseLogUtils.info(logger, "autoChargePay", "信联自动代扣手动触发====结束", CurrentThreadContext.getCurrentUserName());
		return result;
	}

	/**
	 * 计算第三方手续费，返回元
	 * @param PaymentMoney 分
	 * @return
	 */
	public String calFeeAmt(Long PaymentMoney){
		if(null == PaymentMoney) return "0";
		Double feeamt = DecimalUtils.mul(DecimalUtils.convertFenToYuan(PaymentMoney), 0.0012);
		Double min = 1d;
		Double max = 6d;
		int res = this.compare_moneyObj(min, feeamt);
		int res1 = this.compare_moneyObj(feeamt, max);

		if(!"0".equals(min) && res > 0){
			return String.valueOf(min);
		}else if(!"0".equals(max) && res1>0){
			return String.valueOf(max);
		}else{
			return String.valueOf(feeamt);
		}
	}
	/**
	 * 比较两个金额的大小
	 * @param v1
	 * @param v2
	 * @return -1:v2>v1  <br/>0：v1=v2 <br/>  1：v1>v2
	 */
	public static int compare_moneyObj(Object v1, Object v2) {
		BigDecimal b1 = null;
		BigDecimal b2 = null;
		if (v1 != null && !"".equals(String.valueOf(v1))) {
			b1 = new BigDecimal(String.valueOf(v1));
		}else{
			b1 = new BigDecimal("0");
		}
		if (v2 != null && !"".equals(String.valueOf(v2))) {
			b2 = new BigDecimal(String.valueOf(v2));
		}else {
			b2 = new BigDecimal("0");
		}
		return b1.compareTo(b2);
	}
	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.cmmRechargeRecordService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			CmmRechargeRecordVO vo = this.cmmRechargeRecordService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		CmmRechargeRecordVO entity = null;
		try {
			entity = new CmmRechargeRecordVO();
			//TODO ADD PARAM
			Long id = this.cmmRechargeRecordService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String prpslSts = request.getParameter("prpslSts");
		String finResult = request.getParameter("finResult");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		CmmRechargeRecordVO entity = null;
		try {
			entity = new CmmRechargeRecordVO();
			entity.setId(Long.valueOf(id));
			if(StringUtils.isNotEmpty(prpslSts)){
				entity.setPrpslSts(Long.valueOf(prpslSts));
			}
			if(StringUtils.isNotEmpty(finResult)){
				entity.setFinResult(finResult);
			}
			entity.setMdfTm(new Date());
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			boolean success = this.cmmRechargeRecordService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	@RequestMapping(value = "/exportCmmRechargeRecordExcel.do", method = {RequestMethod.POST, RequestMethod.GET})
	public void exportCmmRechargeRecordExcel(HttpServletRequest request, HttpServletResponse response) {
		String orderid = request.getParameter("orderid");
		String isSuc = request.getParameter("isSuc");
		String clientPhone = request.getParameter("clientPhone");
		String clientName = request.getParameter("clientName");
		String platformSeqId = request.getParameter("platformSeqId");
		String crtTmBegin = request.getParameter("crtTmBegin");
		String crtTmEnd = request.getParameter("crtTmEnd");
		String isAutoCharge = request.getParameter("isAutoCharge");

		CmmRechargeRecordQueryCondition qc = new CmmRechargeRecordQueryCondition();
		if (StringUtils.isNotEmpty(orderid)) {
			qc.setId(Long.valueOf(orderid));
		}
		if (StringUtils.isNotEmpty(isSuc)) {
			qc.setIsSuc(Integer.valueOf(isSuc));
		}
		if (StringUtils.isNotEmpty(clientPhone)) {
			qc.setClientPhone(clientPhone);
		}
		if (StringUtils.isNotEmpty(platformSeqId)) {
			qc.setPlatformSeqId(platformSeqId);
		}
		if (StringUtils.isNotEmpty(clientName)) {
			qc.setClientName(clientName);
		}
		if (StringUtils.isNotEmpty(crtTmBegin)) {
			qc.setCrtTmBegin(DateUtils.formatStringToDate(crtTmBegin,DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(crtTmEnd)) {
			qc.setCrtTmEnd(DateUtils.formatStringToDate(crtTmEnd, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(isAutoCharge)) {
			qc.setIsAutoCharge(Integer.valueOf(isAutoCharge));
		}
		List<CmmRechargeRecordVO> list = this.cmmRechargeRecordService.searchList(qc);
		for(CmmRechargeRecordVO _vo : list){
			if(null != _vo.getIsSuc()){
				Map<String,String> sumap = new HashMap<String,String>();
				sumap.put("0","失败");
				sumap.put("1","成功");
				sumap.put("2","未支付");
				sumap.put("3","已受理");
				_vo.setIsSucNm(sumap.get(String.valueOf(_vo.getIsSuc())));
			}
			Long paymentmoney = _vo.getPaymentMoney()!=null?_vo.getPaymentMoney():0l;
			if(null != _vo.getPaymentMoney()){
				_vo.setPaymentMoneydou(DecimalUtils.convertFenToYuan(_vo.getPaymentMoney()));
				_vo.setFeeAmt(this.calFeeAmt(_vo.getPaymentMoney()));
			}
			if(StringUtils.isNotEmpty(_vo.getCommAmt())){
				_vo.setCommAmt(String.valueOf(DecimalUtils.convertFenToYuan(Long.valueOf(_vo.getCommAmt()))));
			}
			if(StringUtils.isNotEmpty(_vo.getPayComm())){
				_vo.setPayComm(String.valueOf(DecimalUtils.convertFenToYuan(Long.valueOf(_vo.getPayComm()))));
			}
			if(null != _vo.getCommPayType()){
				Map<String,String> commpaytypemap = new HashMap<String,String>();
				commpaytypemap.put("0","狮桥支付");
				commpaytypemap.put("1","用户支付");
				commpaytypemap.put("2","免费");
				_vo.setCommPayTypeNm(commpaytypemap.get(String.valueOf(_vo.getCommPayType())));
			}
			if(null != _vo.getPayType()){
				Map<String,String> paytypemap = new HashMap<String,String>();
				paytypemap.put("1","汇付");
				paytypemap.put("2","信联");
                paytypemap.put("3","国付宝");
				_vo.setPayTypeNm(paytypemap.get(String.valueOf(_vo.getPayType())));
			}
			if(null != _vo.getPaymentType()){
				Map<String,String> paymenttypemap = new HashMap<String,String>();
				paymenttypemap.put("1","快捷支付");
				paymenttypemap.put("2","代扣支付");
				_vo.setPaymentTypeNm(paymenttypemap.get(String.valueOf(_vo.getPaymentType())));
			}
			if(null != _vo.getIsAutoCharge()){
				Map<String,String> isautochargemap = new HashMap<String,String>();
				isautochargemap.put("1","是");
				isautochargemap.put("0","否");
				_vo.setIsAutoChargeNm(isautochargemap.get(String.valueOf(_vo.getIsAutoCharge())));
			}
		}
		ExportParams params = new ExportParams("还款记录", "还款记录", ExcelType.HSSF);
		//HSSF是POI工程对Excel 97(-2007)文件操作的纯Java实现;
		//XSSF是POI工程对Excel 2007 OOXML (.xlsx)文件操作的纯Java实现
		//SXSSF基于XSSF的低内存占用的API
		params.setColor(HSSFColor.BRIGHT_GREEN.index);//表头颜色
		params.setStyle(ExcelExportStylerDefaultImpl.class);//ExcelExportStylerBorderImpl 有边框样式 ExcelExportStylerColorImpl  有边框间隔行样式 ExcelExportStylerDefaultImpl	默认的样式
		Workbook workbook = ExcelExportUtil.exportExcel(params, CmmRechargeRecordVO.class, list);
		OutputStream ouputStream = null;
		try {
			String filename="还款记录";
			filename=new String(filename.getBytes("UTF-8"),"ISO8859-1");
			response.reset();
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");// 设定输出文件头
			response.setContentType("application/x-msdownload");// 定义输出类型
			ouputStream = response.getOutputStream();
			workbook.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (UnsupportedEncodingException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
		} catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
		}finally {
			//关闭流
			if(ouputStream!=null){
				try {
					ouputStream.close();
				} catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
				}
			}
		}
	}

	/**
	 * 支付成功分解失败批量处理
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/autoFundDecompose.do", method = { RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public DataResultVO autoFundDecompose(HttpServletRequest request, HttpServletResponse response) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "分解执行中...");
		BaseLogUtils.info(logger, "autoFundDecompose", "支付成功分解失败批量处理====开始", CurrentThreadContext.getCurrentUserName());
		this.cmmRechargeRecordService.autoFundDecompose();
		BaseLogUtils.info(logger, "autoFundDecompose", "支付成功分解失败批量处理====结束", CurrentThreadContext.getCurrentUserName());
		return result;
	}


	/**
	 * 支付成功订单分解
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/fundDecompose.do", method = { RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public DataResultVO fundDecompose(HttpServletRequest request, HttpServletResponse response) {

		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "已发起订单分解，请稍后查看分解结果");
		if (StringUtils.isEmpty(id)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "fundDecompose", "订单分解,订单id不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		CmmOlRecordDetailQueryCondition condition = new CmmOlRecordDetailQueryCondition();
		condition.setRecordId(Long.valueOf(id));
		List<CmmOlRecordDetailVO> list = cmmOlRecordDetailService.searchList(condition);
		if (list.size() > 0){
			Integer isDecsuc = list.get(0).getIsDecSuc();
			if (isDecsuc == 2 || isDecsuc == 0) {
				BaseLogUtils.info(logger, "fundDecompose", "支付成功订单分解处理====开始", CurrentThreadContext.getCurrentUserName());
				this.cmmRechargeRecordService.fundDecompose(Long.valueOf(id));
				BaseLogUtils.info(logger, "fundDecompose", "支付成功订单分解处理====结束", CurrentThreadContext.getCurrentUserName());
			}else {
				result = new DataResultVO(BaseConstant.IS_YESNO_NO, "订单已经分解成功,无需再做分解");
			}
		}

		return result;
	}


	/**
	 * 获取渠道信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getChlInfo.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object getChlInfo(HttpServletRequest request, HttpServletResponse response){

		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "getByOrderId", "根据平台订单号获取对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		String orderid = request.getParameter("orderid");

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");

		if(StringUtils.isEmpty(orderid)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("平台订单号为空!");
			BaseLogUtils.error(logger, "getByOrderId", "获取渠道信息,平台订单号不存在.[localSeqId="+orderid+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			String channelNm = cmmRechargeRecordService.queryChl(orderid, "1");
			BaseLogUtils.info(logger, "getChlInfo", "获取到的渠道信息", channelNm);
			if(channelNm != null){
				result.setData(channelNm);
			}else {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在!");
				BaseLogUtils.info(logger, "getByOrderId", "获取订单信息,数据不存在.[id="+orderid+"]", CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "getByOrderId", "获取订单信息.[id="+orderid+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getByOrderId", "根据平台订单号获取信息失败,主键["+orderid+"].", CurrentThreadContext.getCurrentUserName(),ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "getByOrderId", "根据平台订单号获取信息失败,主键["+orderid+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "getByOrderId", "根据平台订单号获取对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

		return result;
	}
}



